
/**
 * @version $Id$
 * @author xjiujiu <xjiujiu@foxmail.com>
 * @description HongJuZi Framework
 * @copyright Copyright (c) 2011-2012 http://www.xjiujiu.com.All right reserved
 */

HHJsLib.register({
    init: function() {
        this.bindBtnAttributeAdd('#btn-add-new-category, a.btn-attribute-add');
        this.bindBtnAttributeDel('a.btn-attribute-del');
        this.bindBtnGenerateSku();
        this.bindInfoFromSubmit();
        this.bindSKUNumberChange('#sku-list input.sku-number');
        this.bindSKUOrdersChange('#sku-list input.sku-orders');
        this.bindDrop();
        this.bindBtnAttDel('a.btn-attr-item-del');
        this.bindSKUPriceChange();
        this.bindDiscountChange();
        this.bindAttrChange();
        this.bindDelColorImage();
    },
    bindDelColorImage: function() {
        $('.delete-color-image').click(function() {
            var id = $(this).attr('data-id');
            if (confirm('确认删除吗?')) {
                $('.color-box-' + id).remove();
            }
        });
    },
    bindShopIdChange: function() {
        var self    = this;
        var shopId  = $('#shop_id');
        require([cdnUrl + "/jquery/plugins/chosen/chosen.jquery.js"], function() {
            $('#shop_id').chosen().change(function() {
                if(shopId == $(this).val()) {
                    return;
                }
                shopId  = $(this).val();
                self.loadShopExpressList(shopId);
            });
        });
    },
    loadShopExpressList: function(shopId) {
        var optHtml     = '<option value="">请选择</option>';
        if(!shopId) {
            $('#baoyou_express').html(optHtml).trigger("chosen:updated");
            return;
        }
        $.getJSON(
            queryUrl + 'admin/goodsbaoyou/alist',
            {shopId: shopId},
            function(response) {
                if(false === response.rs) {
                    return HHJsLib.warn(response.message);
                }
                for(var ele in response.data) {
                    var item    = response.data[ele];
                    optHtml     += '<option value="' + item.id + '">' + item.name + '</option>';
                }
                $('#baoyou_express').html(optHtml);
                HHJsLib.autoSelect('#baoyou_express');
                $('#baoyou_express').trigger("chosen:updated");
            }
        );
    },
    bindSKUNumberChange: function(target) {
        var self    = this;
        $(target).change(function() {
            self.reCountTotalNumber();
        });
    },
    bindSKUOrdersChange: function(target) {
        var self    = this;
        $(target).change(function() {
            self.reCountTotalOrders();
        });
    },
    reCountTotalOrders: function() {
        var total   = 0;
        $('#sku-list input.sku-orders').each(function() {
            var number  = $(this).val();
            number      = !number ? 0 : parseInt(number);
            total       += 0 > number ? 0 : number;
        });
        $('#total_orders').val(total);
    },
    reCountTotalNumber: function() {
        var total   = 0;
        $('#sku-list input.sku-number').each(function() {
            var number  = $(this).val();
            number      = !number ? 0 : parseInt(number);
            total       += 0 > number ? 0 : number;
        });
        $('#total_number').val(total);
    },
    bindBtnAttributeAdd: function(dom) {
        var self = this;
        $(dom).unbind().click(function() {
            var id          = $(this).attr('data-id');
            var title       = '添加新规格';
            var content     = $('#add-attribute-tpl').html();
            $('#myModalLabel').html(title);
            $('#myModal').find('#modal-body').html(content);
            if('undefined' !== typeof(id)) {
                self.doSearchAttrList(1, id);
            }
            $('#myModal').modal('show');
            self.bindCategoryChange();
            self.bindBtnAttrSearchFormSubmit();
        });
    },
    bindCategoryChange: function() {
        $('#category').change(function() {
            if(!$('#category').val()) {
                return;
            }
            $('#attr-search-form').submit();
        });
    },
    bindBtnAttrSearchFormSubmit: function() {
        var self    = this;
        $('#attr-search-form').submit(function() {
            try {
                HHJsLib.isEmptyByDom('#category', '分类编号');
                self.doSearchAttrList(1, $('#category').val());
                return false;
            } catch(e) {
                return HHJsLib.warn(e);
            }
        });
    },
    doSearchAttrList: function(page, catId) {
        var self        = this;
        var keyword     = $('#attr-keyword').val();
        $.getJSON(
            queryUrl + 'admin/attribute/alist',
            {keyword: keyword, page: page, parent_id: catId},
            function(response) {
                if(false === response.rs) {
                    return HHJsLib.warn(response.message);
                }
                $('#search-attr-page').val(page + 1);
                var tableTpl    = $('#search-attr-result-tpl').html();
                var itemHtml    = self.getSearchAttrListHtml(response.data, catId);
                tableTpl        = tableTpl.replace(/{content}/g, itemHtml);
                $('#attr-table-box').html(tableTpl);
                var prePage     = page - 1 > 0 ? page - 1 : 1;
                var nextPage    = page + 1 > response.totalPages ? response.totalPages : page + 1;
                $('#cur-cat-id').val(catId);
                self.bindBtnAddAttrToGoods();
                self.bindBtnAddAttrBatch();
                self.bindCheckAttrAll();
                self.initSearchTablePages(page, response);
                self.bindBtnPreNextSearchPages(function(page) {
                    self.doSearchAttrList(page);
                });
            },
            'JSON'
        );
    },
    getSearchAttrListHtml: function(list, catId) {
        if(!list || 1 > list.length) {
            return '<tr><td colspan="4"><div  class="text-center">没有相关规格哦～，<a href="' + queryUrl + 'admin/attribute/addview" target="_blank">去新增规格</a></div></td></tr>';
        }
        var itemTpl = $('#result-attr-item-tpl').html();
        var tdHtml  = '';
        for(var ele in list) {
            var item    = list[ele];
            tdHtml      += itemTpl.replace(/{id}/g, item.id)
                .replace(/{name}/g, item.name)
                .replace(/{cat_id}/g, catId)
                .replace(/{admin_name}/g, item.admin_name);
        }

        return tdHtml;
    },
    bindBtnAttDel: function(dom) {
        $(dom).click(function() {
            var id      = $(this).attr('data-id');
            var $parent = $('#attr-' + id);
            var status  = $parent.attr('data-status');
            if(1 == status) {
                $parent.fadeOut('fast', function() {
                    $(this).remove();
                });
                return;
            }
            HHJsLib.info('正在删除中...');
            $.getJSON(
                queryUrl + 'admin/skuattribute/adelitem',
                {goods_id: $('#id').val(), id: id},
                function(response) {
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    $parent.fadeOut('fast', function() {
                        $(this).remove();
                    });
                    HHJsLib.info('属性已经变更，请重新生成规格组合！');
                }
            );
        });
    },
    bindCheckAttrAll: function() {
        $('#search-check-attr-all').on('click' , function(){
            var that = this;
            $('#attr-table-box tr > td input.que-checkbox').each(function(){
                this.checked = that.checked;
                $(this).closest('tr').toggleClass('selected');
            });
        });
    },
    initSearchTablePages: function(page, response) {
        var prePage     = page - 1 > 0 ? page - 1 : 1;
        var nextPage    = page + 1 > response.totalPages ? response.totalPages : page + 1;
        $('#btn-btn-search-pre-page').attr('data-page', prePage);
        $('#btn-btn-search-next-page').attr('data-page', nextPage);
        $('#cur-page-info').html(page + ' / ' + response.totalPages);
        $('#btn-search-next-page,#btn-search-pre-page').attr('disabled', null);
        if(1 == response.totalPages) {
            $('#btn-search-next-page,#btn-search-pre-page').attr('disabled', 'disabled');
        } else if(1 >= page) {
            $('#btn-search-pre-page').attr('disabled', 'disabled');
        } else if (page == response.totalPages) {
            $('#btn-search-next-page').attr('disabled', 'disabled');
        }
    },
    bindBtnPreNextSearchPages: function(callback) {
        $('#btn-search-next-page,#btn-search-pre-page').click(function() {
            if(null != $(this).attr('disabled')) {
                return false;
            }
            var page    = $(this).attr('data-page');
            if('undefined' !== typeof(callback)) {
                return callback(page);
            }
        });
    },
    bindBtnAddAttrToGoods: function() {
        var self    = this;
        $('#attr-table-box a.btn-add-search-attr').click(function() {
            var id      = $(this).attr('data-id');
            var catId   = $(this).attr('data-cat-id');
            self.appendAttrList(id, catId);
            $('#search-attr-item-' + id).fadeOut('fast', function() {
                $(this).remove();
            });
        });
    },
    appendAttrList: function(id, catId) {
        var tpl             = $('#attr-item-tpl').html();
        var attrItem        = $('#cat-list-' + catId).find('#attr-' + id).length;
        if(attrItem > 0){
            return false;
        }
        tpl                 = tpl.replace(/{name}/g, $('#name-' + id).text())
            .replace(/{admin_name}/g, $('#admin-name-' + id).text())
            .replace(/{id}/g, id)
            .replace(/{cat_id}/g, catId);
        $catAttrBox         = $('#cat-attr-box-' + catId);
        if(1 > $catAttrBox.length) {
            this.appendAttrCatBox(catId);
        }
        $('#cat-list-' + catId).append(tpl);
        this.bindBtnAttDel('#cat-list-' + catId + ' a.btn-attr-item-del');
    },
    appendAttrCatBox: function(catId) {
        var category    = $("#category").find("option:selected").text();
        var tpl         = $('#cat-attr-box-tpl').html();
        tpl             = tpl.replace(/{id}/g, catId)
        .replace(/{category}/g, category);
        $('#accordion-attr-box').append(tpl);

        this.bindDrop('#cat-list-box-' + catId);
        this.bindBtnAttributeAdd('#cat-attr-box-' + catId + ' a.btn-attribute-add');
        this.bindBtnAttributeDel('#cat-attr-box-' + catId + ' a.btn-attribute-del');
    },
    bindBtnAttributeDel: function(dom) {
        $(dom).click(function() {
            if(!confirm('您真的要删除此类下所有的属性吗？')) {
                return false;
            }
            var id      = $(this).attr('data-id');
            var status  = $('#cat-attr-box-' + id).attr('data-status');
            $('#cat-attr-box-' + id).fadeOut('fast', function() {
                $(this).remove();
            });
            if(1 == status) {
                HHJsLib.info('属性已经变更，请重新生成您的规格组合！');
                return;
            }
            HHJsLib.info('正在删除中...');
            var ids     = $('#cat-list-box-' + id).nestable('serialize');
            $.getJSON(
                queryUrl + 'admin/skuattribute/adelbygoods',
                {ids: JSON.stringify(ids), goods_id: $('#id').val()},
                function(response) {
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    $('#cat-attr-box-' + id).fadeOut('fast', function() {
                        $(this).remove();
                    });
                    HHJsLib.info('属性已经变更，请重新生成您的规格组合！');
                }
            );
        });
    },
    bindBtnAddAttrBatch: function() {
        var self    = this;
        $('#myModal a.btn-add-attr-batch').on('click', function(){
            try{
                var items       = $("#search-attr-list input:checked");
                if(typeof items.length == 'undefined' || items.length < 1 ) {
                    return HHJsLib.warn("请选择要添加的规格！");
                }
                items.each(function(){
                    var id      = $(this).val();
                    var catId   = $(this).attr('data-cat-id');
                    self.appendAttrList(id, catId);
                    $('#search-attr-item-' + id).fadeOut('fast', function() {
                        $(this).remove();
                    });
                });
            } catch(e) {
                return HHJsLib.warn(e);
            }
        });
    },
    bindInfoFromSubmit: function() {
        var self    = this;
        $('#info-form').submit(function() {
            try{
                if($('#name').val() == ''){
                    $('#name').focus();
                    return false;
                }
                if($('#mk_price').val() == ''){
                    $('#mk_price').focus();
                    return false;
                }
                if(HHJsLib.editor.content.getContent() == ''){
                    HHJsLib.editor.content.focus();
                    return false;
                }
                HHJsLib.isEmptyByDom('#image_path', '封面图片');
                var next = false;
                var len = $('#sku-list').children('tr').length;
                if(1 > len){
                    // return HHJsLib.warn('价格及属性规格组合不能为空');
                }
                $('#sku-list').children('tr').each(function(index) {
                    var $that = $(this);
                    if($that.find('input.sku-price').val() == ''){
                        next = true;
                        return HHJsLib.warn('第' + (index + 1) + '个规格参数的原价不能为空');
                    }
                    if($that.find('input.sku-miaosha-price').val() == ''){
                        next = true;
                        return HHJsLib.warn('第' + (index + 1) + '个规格参数的秒杀价不能为空');
                    }
                    if($that.find('input.sku-yusho-price').val() == ''){
                        next = true;
                        return HHJsLib.warn('第' + (index + 1) + '个规格参数的预售价不能为空');
                    }
                    if($that.find('input.sku-tuan-price').val() == ''){
                        next = true;
                        return HHJsLib.warn('第' + (index + 1) + '个规格参数的拼团价不能为空');
                    }
                    if($that.find('input.sku-choujiang-price').val() == ''){
                        next = true;
                        return HHJsLib.warn('第' + (index + 1) + '个规格参数的抽奖价不能为空');
                    }
                    if($that.find('input.sku-number').val() == ''){
                        next = true;
                        return HHJsLib.warn('第' + (index + 1) + '个规格参数的库存不能为空');
                    }
                    /*if($that.find('input[name="sku_image_path[]"]').val() == ''){
                        next = true;
                        return HHJsLib.warn('第' + (index + 1) + '个规格参数的图片不能为空');
                    }*/
                });
                if(next){
                    return false;
                }
                self.reCountTotalNumber();
                $('div.dd').each(function() {
                    var $this       = $(this);
                    var obj         = $this.nestable('serialize');
                    var str         = JSON.stringify(obj);
                    $this.find('input:hidden').val(str);
                });
            } catch(e) {
                return HHJsLib.warn(e);
            }
        });
    },
    bindBtnGenerateSku: function() {
        var self    = this;
        $('#btn-generate-sku').click(function() {
            try{
                self.initSkuList();
            } catch(e) {
                return HHJsLib.warn(e);
            }
        });
    },
    initSkuList: function() {
        var t       = (new Date()).getTime();
        var tpl     = $('#sku-item-tr-tpl').html();
        var tplHtml = '';
        var colorid = $('#color-box').val();
        var name    = $('#color-box').find("option:selected").text();
        tplHtml     = tpl.replace(/{name}/g, name)
        .replace(/{id}/g, t)
        .replace(/{colorid}/g, colorid)
        formData['sku-img-' + t]   = {
            'timestamp' : t,
            'token'     : hex_md5(t),
            'model'     : 'skugoods',
            'field'     : 'image_path',
            'nolinked'  : 1
        };
        $('#sku-list').append(tplHtml);
        HHJsLib.bindLightBox('#sku-list a.lightbox', cdnUrl + 'jquery/plugins/lightbox');
        this.bindDelColorImage();
        //HJZInfoUploadFile.bindBtnFile("#sku-list button.btn-file");
		HJZInfoUploadFile.bindBtnFile("#sku-img-" + t);
    },
    bindDiscountChange: function() {
        var self    = this;
        $('#discount').change(function() {
            var val     = $(this).val();
            if(val > 10) {
                $(this).val(10);
                return HHJsLib.warn('折扣不能大于10折！');
            }
            if(val < 1) {
                $(this).val(10);
                return HHJsLib.warn('折扣不能小于1折！');
            }
            self.reCountAllDicountPrice();
        });
    },
    reCountAllDicountPrice: function() {
        var self    = this;
        $('#sku-list input.sku-price').each(function() {
            var price   = $(this).val();
            return self.countDiscountPrice($(this), price);
        });
    },
    countDiscountPrice: function($this, price) {
        var id      = $this.parent().parent().attr('data-id');
        if(!price) {
            $('#sku-cheap-price-' + id).val('');
            return true;
        }
        if(0 > price) {
            $this.val(0).focus();
            return HHJsLib.warn('价钱不能小于0元！');
        }
        var discount= $('#discount').val();
        price       = parseFloat(price);
        discount    = !discount ? 10 : discount;
        var total   = price * discount / 10;
        $('#sku-cheap-price-' + id).val(total.toFixed(2));
    },
    bindSKUPriceChange: function() {
        var self        = this;
        $('#sku-list input.sku-price').change(function() {
            var price   = $(this).val();
            var id      = $(this).parent().parent().attr('data-id');
            if(!$('#sku-miaosha-price-' + id).val()) {
                $('#sku-miaosha-price-' + id).val(price);
            }
            if(!$('#sku-yusho-price-' + id).val()) {
                $('#sku-yusho-price-' + id).val(price);
            }
            if(!$('#sku-tuan-price-' + id).val()) {
                $('#sku-tuan-price-' + id).val(price);
            }
            if(!$('#sku-choujiang-price-' + id).val()) {
                $('#sku-choujiang-price-' + id).val(price);
            }
            self.countDiscountPrice($(this), price);
        });
    },
    bindDrop: function(target) {
        target  = 'undefined' == typeof(target) ? 'div.dd' : target;
        $(target).nestable({'maxDepth': 1}).on('change', function() {
            var that        = $(this);
            var obj         = that.nestable('serialize');
            var str         = window.JSON.stringify(obj);
            that.find('input:hidden').first().val(str);
        });
    },
    bindAttrChange: function() {
        $('#tab-step-attr').on('click', function() {
            $('#color_box_chosen').css({width:'125px'});
        });
    }
});
